package cn.cyb.server.security.handler;

import cn.cyb.server.common.constant.HttpStatus;
import cn.cyb.server.common.utils.JsonUtils;
import cn.cyb.server.common.utils.ServletUtils;
import cn.cyb.server.domain.AjaxResult;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 认证失败处理类 返回未授权
 *
 * @author yuebo
 * @date 2024/12/25
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    private Logger logger = LoggerFactory.getLogger(AuthenticationEntryPointImpl.class);

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        String msg = String.format("请求访问：%s，认证失败，无法访问系统资源", request.getRequestURI());
        logger.info(msg);
        AjaxResult ajaxResult = AjaxResult.error(HttpStatus.UNAUTHORIZED, msg);
        ServletUtils.renderString(response, JsonUtils.toJsonString(ajaxResult));
    }
}
